package com.qdaily.ui.ui.views.QDWebView.QDArticleWebViewFileCache;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;

import com.qdaily.supportlibrary.cache.DiskFileUtils;
import com.qdaily.supportlibrary.util.Encrypt;
import com.qdaily.supportlibrary.util.QLog;
import com.qdaily.ui.data.EventModel.EventQFileDownComplete;
import com.tencent.mm.sdk.platformtools.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;

import com.qdaily.ui.util.BusProvider;

/**
 * Created by song on 15/5/8.
 */
public class QDArticleWebViewFileCacheMgr implements QDArticleWebViewFileDownloadSlave.DownloadInteface {
    private static QDArticleWebViewFileCacheMgr shareInstance;
    private Set<String> curDownloading;

    public String CacheFilePath;
    public String ArticleCacheFilePath;
    public boolean isReady; //是不是准备好了
    private final String TAG = "QDArticleWebViewFileCacheMgr";

    public static final String QDailyArticleExt = "#QDailyArticleExt";
    private Context mContext;

    private long maxCacheSize = 1000*1000*300; //默认300m图片吧

    private QDArticleWebViewFileCacheMgr() {
    }

    public void init(Context context, DownCompleteHandler handler) {
        this.mContext = context;
        this.handler = handler;
        DiskFileUtils.CacheDirInfo cacheDirInfo = DiskFileUtils.getDiskCacheDir(context, "WebviewCache", maxCacheSize);
        CacheFilePath = cacheDirInfo.path.getAbsolutePath();
        cacheDirInfo = DiskFileUtils.getDiskCacheDir(context, "ArticleCache", maxCacheSize);
        ArticleCacheFilePath = cacheDirInfo.path.getAbsolutePath();
        curDownloading = new HashSet<String>();
        isReady = isFolderExists(CacheFilePath) && isFolderExists(ArticleCacheFilePath);
        Log.i(TAG, "CacheFilePath = " + CacheFilePath);
    }

    public static QDArticleWebViewFileCacheMgr getInstance() {
        if (shareInstance == null) {
            shareInstance = new QDArticleWebViewFileCacheMgr();
        }
        return shareInstance;
    }

    public void clearCurCache()
    {
        if (CacheFilePath != null && isFolderExists(CacheFilePath))
        {
            File file = new File(CacheFilePath);
            File[] childFiles = file.listFiles();
            for (File childFile : childFiles) {
                QLog.w(TAG, "delete:" + childFile.getAbsolutePath());
                childFile.delete();
            }
        }

        if (ArticleCacheFilePath != null && isFolderExists(ArticleCacheFilePath))
        {
            File file = new File(ArticleCacheFilePath);
            File[] childFiles = file.listFiles();
            for (File childFile : childFiles) {
                QLog.w(TAG, "delete:" + childFile.getAbsolutePath());
                childFile.delete();
            }
        }
    }

    /*
    *
    */
    boolean isFolderExists(String strFolder) {
        File file = new File(strFolder);
        if (!file.exists()) {
            if (file.mkdirs()) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    public InputStream getLocalCache(String url, boolean isArticle) throws IOException {
        if (!isReady) {
            QLog.e(TAG, "isReady = false");
            return null;
        }

        String hash = Encrypt.md5(url);
        InputStream localCopy = inputStreamFromFileName(hash, isArticle);
        if (localCopy == null) {
            QLog.w(TAG, "本地不存在:" + hash + ",url:" + url);
            synchronized (curDownloading) {
                if (!curDownloading.contains(hash)) {
                    curDownloading.add(hash);
                    ThreadExecutor.execute(new QDArticleWebViewFileDownloadSlave(url, isArticle ? ArticleCacheFilePath : CacheFilePath, hash, this));
                }
            }
        } else {
            QLog.w(TAG, "cache命中:" + hash + ",url:" + url);
        }
        return localCopy;
    }

    public File getLocalCacheFile(String url, boolean isArticle) {

        if (!isReady) {
            QLog.e(TAG, "isReady = false");
            return null;
        }

        String hash = Encrypt.md5(url);
        File file = new File( isArticle ? ArticleCacheFilePath : CacheFilePath, hash);
        if (file.exists())
        {
            return file;
        } else {
            return null;
        }
    }

    public File getLocalGifCache(String url) {
        if (!isReady) {
            QLog.e(TAG, "isReady = false");
            return null;
        }

        String hash = Encrypt.md5(url);
        File file = new File( CacheFilePath, hash);
        if (!file.exists()) {
            QLog.w(TAG, "本地不存在:" + hash + ",url:" + url);
            synchronized (curDownloading) {
                if (!curDownloading.contains(hash)) {
                    curDownloading.add(hash);
                    ThreadExecutor.execute(new QDArticleWebViewFileDownloadSlave(url, CacheFilePath, hash, this));
                }
            }
            return null;
        }
        else {
            QLog.w(TAG, "gif cache命中:" + hash + ",url:" + url);
            return file;
        }
    }

    @Nullable
    private InputStream inputStreamFromFileName(String name, boolean isArticle) {
        File f = new File(isArticle ? ArticleCacheFilePath : CacheFilePath, name);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(f);
        } catch (IOException e) {

        }
        return inputStream;
    }

    @Override
    public void complete(String url, String name, String filePath, boolean success) {
        Thread a = Thread.currentThread();
        QLog.w(TAG, a.getId() + "-下载完成:" + name + ",url:" + url);
        EventQFileDownComplete event = new EventQFileDownComplete();
        event.setName(name);
        event.setFilePath(filePath);
        event.setSuccess(success);
        event.setUrl(url);
        synchronized (curDownloading) {
            curDownloading.remove(name);
            if (handler != null) {
                handler.sendMessage(handler.obtainMessage(DownCompleteTag, event));
            }
        }
    }

    private DownCompleteHandler handler;

    public static final int DownCompleteTag = 0x19234;

    public static class DownCompleteHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == QDArticleWebViewFileCacheMgr.DownCompleteTag) {
                EventQFileDownComplete event = (EventQFileDownComplete) msg.obj;
                BusProvider.getInstance().post(event);
            }
        }
    }
}